<?php

namespace app\api\Logic\Course;

use app\api\Logic\Campusclass\CampusClassLogic;
use app\api\model\CampusCourseOrderSublevelModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;

class OrderSublevelLogic
{
    /**
     * 获取已购买课程列表
     * @param $params
     * @param string $field
     * @return array
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getCourseList($params,$field = "*"){
        $shopId = $params['shop_id'] ?? 0;
        $userId = $params['user_id'] ?? 0;

        if(empty($shopId) || empty($userId)){
            throw new Exception('校区ID或用户ID必须',0);
        }

        $list = CampusCourseOrderSublevelModel::where('shop_id',$shopId)
            ->where('user_id',$userId)
            ->where('type',3)
            ->where('status',1)
            ->with([
                'managementCourse' => function ($query) {
                    $query->withField('id,class_type');
                }
            ])
            ->field($field)
            ->select();
        return objToArray($list) ?? [];
    }

    /**
     * 获取学员在某个班级下的课时信息,只返回最高课时
     * @param $shopId
     * @param $userId
     * @param $classId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function getMaxCourseHourByClassId($shopId,$userId,$classId){
        //最终返回的最高课时信息
        $res = ['course_hour' => 0,'course_hour_type' => 'hour'];

        $campusClassLogic = new CampusClassLogic();

        //返回学员所有下单课程
        $getCourseList = $this->getCourseList(['shop_id' => $shopId,'user_id' => $userId],"id,gs_id,all_num,use_num,m_type,m_type_num");

        if(!empty($getCourseList)){
            //学员下单课程ID
            $courseIds = array_column($getCourseList,'gs_id');
            //本次需验证的课程ID，由于不是所有课程都是同一个班级，因此需要根据班级判断，最终获取该班级下的课程，并且根据这些课程返回最高课时信息
            $needVerifyCourseIds = [];

            //根据课程ID反向查询班级
            $classList = $campusClassLogic->getClassByCourseIds($shopId,$courseIds);
            foreach ($classList as $classInfo){
                if($classInfo['id'] == $classId){
                    //班级下的课程ID
                    $classCourseIds = !empty($classInfo['course_id']) ? explode(',',$classInfo['course_id']) : [];
                    foreach ($courseIds as $courseId){
                        if(in_array($courseId,$classCourseIds)){
                            $needVerifyCourseIds[] = $courseId;
                        }
                    }
                }
            }

            foreach ($getCourseList as $courseInfo){
                if(in_array($courseInfo['gs_id'],$needVerifyCourseIds)){
                    //剩余课时
                    $surplusNum = $courseInfo['all_num'] - $courseInfo['use_num'];

                    if($courseInfo['m_type'] == 'hour' && $res['course_hour_type'] == 'hour' && $res['course_hour'] < $surplusNum){
                        //课时类型为时并且学员最高课时类型也为时，并且最高课时小于当前课程的剩余课时，则重新赋值
                        $res['course_hour'] = $courseInfo['all_num'] - $courseInfo['use_num'];
                    }else if($courseInfo['m_type'] == 'monthly' && $surplusNum > 0){
                        //课时类型为月，并且剩余课时大于0
                        if($res['course_hour_type'] == 'hour' || $res['course_hour_type'] == 'day'){
                            //若最高课时类型为时或者天，则直接赋值
                            $res = ['course_hour' => $surplusNum,'course_hour_type' => 'monthly'];
                        }else if($res['course_hour_type'] == 'monthly' && $res['course_hour'] < $surplusNum){
                            $res['course_hour'] = $surplusNum;
                        }
                    }else if($courseInfo['m_type'] == 'day' && (in_array($res['course_hour_type'],['hour','day'])) && $surplusNum > 0){
                        //课时类型为天并且学员最高课时类型为时或者天，并且剩余课时大于0
                        if($res['course_hour_type'] == 'hour'){
                            //若最高课时类型为时，则直接赋值
                            $res = ['course_hour' => $surplusNum,'course_hour_type' => 'day'];
                        }else if($res['course_hour_type'] == 'day' && $res['course_hour'] < $surplusNum){
                            $res['course_hour'] = $surplusNum;
                        }
                    }
                }
            }
        }

        return $res;
    }
}
